// HTTP请求封装
const app = getApp()
const URL = app.globalData.webSiteUrl


export default class Api {
  static ajax(url, data, method = 'POST') {
    wx.showLoading({
      title: '加载中',
    });
      //将wx默认的request 封装成 promise
      return new Promise((resolve, reject) => {
        wx.request({
          url: `${URL}${url}`,
          data: data,
          method: method,
          header: {
            "Authorization": "Bearer " + wx.getStorageSync('userInfo').token,
            "content-type": 'application/json' // 默认值
          },
          success(res) {
            resolve(res['data']);
            if (res['data']) {
              // if (res['data']['code'] == 501 || res['data']['code'] == 502) {
              //   wx.redirectTo({
              //     url: '/pages/member/login/login'
              //   })
              // }
            }
          },
          fail(reject) {
            wx.showModal({
              title: '网络错误',
              content: '连接服务器失败',
              showCancel: true,
              cancelText: '取消',
              confirmText: '重试',
            });
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      })
    
  }
  //加载时动画

  // 提示
  static showTost(txt) {
    wx.showToast({
      title: txt,
      icon: 'none',
    })
  }
  /*错误提示 */
  static errorTost(txt) {
    wx.showToast({
      title: txt,
      icon: 'error',
      image: '/images/login/error.png',
      duration: 2000
    })
  }
  /* 倒计时*/
  static getCode(_this, num) {
    _this.setData({
      isShow: true
    })
    var remain = num;
    var time = setInterval(function () {
      if (remain == 1) {
        clearInterval(time);
        _this.setData({
          sec: num,
          isShow: false
        })
        return false //必须有
      }
      remain--;
      _this.setData({
        sec: remain
      })
    }, 1000)
  }

  /*判断是否的登录*/
  static isLogin() {
    var token = wx.getStorageSync('token') || [];
    if (token == '' || Object.prototype.toString.call(token) === '[object Undefined]') {

      wx.redirectTo({
        url: '',
      })
    }
  }
  static formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }
  /** 
   * 时间戳转化为年 月 日 时 分 秒 
   * number: 传入时间戳 
   * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
   */
  static formatTime(number, format) {

    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];

    var date = new Date(number * 1000);
    returnArr.push(date.getFullYear());
    returnArr.push(this.formatNumber(date.getMonth() + 1));
    returnArr.push(this.formatNumber(date.getDate()));

    returnArr.push(this.formatNumber(date.getHours()));
    returnArr.push(this.formatNumber(date.getMinutes()));
    returnArr.push(this.formatNumber(date.getSeconds()));

    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  }
  //倒计时
  static order_down(_this, miu, sec) {
    var remiu = miu;
    var remain = sec;
    var time = setInterval(function () {
      if (remiu <= 0 && remain <= 1) {
        clearInterval(time);
        remiu = 0;
        remain = 0;
        _this.setData({
          sec: remain,
          miu: remiu,
          isShow: false
        })
        return false //必须有
      } else {
        if (remain <= 0) {
          if (remiu > 0) {
            remain = 59;
            --remiu;
            _this.setData({
              miu: remiu,
              sec: remain
            });
          } else {
            remain = 0;
            remiu = 0;
            _this.setData({
              miu: remain,
              sec: remiu
            })
          }

        } else {
          if (remain >= 0) {
            remain--;
            _this.setData({
              sec: remain
            })
          } else {
            remain = 0;
            _this.setData({
              sec: remain
            })
          }
        }
      }

    }, 1000)
  }
  /**时间戳转星期 */
  static getWeek(timedat) {
    var newDate = new Date();
    newDate.setTime(timedat);
    var week;
    if (newDate.getDay() == 0) week = "周日";

    if (newDate.getDay() == 1) week = "周一";

    if (newDate.getDay() == 2) week = "周二";

    if (newDate.getDay() == 3) week = "周三";

    if (newDate.getDay() == 4) week = "周四";

    if (newDate.getDay() == 5) week = "周五";

    if (newDate.getDay() == 6) week = "周六";

    return week;
  }
  /**
   * today 是需要计算的某一天的日期例如“2017-07-07”，传 null 默认今天
   * addDayCount 是要推算的天数， -1是前一天，0是今天，1是后一天，以此类推
   */
  static getDateStr(today, addDayCount) {
    var dd;
    if (today) {
      dd = new Date(today);
    } else {
      dd = new Date();
    }
    dd.setDate(dd.getDate() + addDayCount); //获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期 
    var d = dd.getDate();
    if (m < 10) {
      m = '0' + m;
    };
    if (d < 10) {
      d = '0' + d;
    };
    return y + "-" + m + "-" + d;
  }
  static formatString(str) {
    if (typeof (str) != "string") {
      console.log('去除回车换行空格失败！参数不是字符串类型')
      return;
    }
    str = str.replace(/\ +/g, ""); //去掉空格
    str = str.replace(/[\r\n]/g, ""); //去掉回车换行
    return str;
  }


}